package cn.chiship.framework.upms.biz.system.controller;


import cn.chiship.framework.upms.biz.base.service.CacheService;
import cn.chiship.framework.upms.biz.system.service.UpmsEmailSettingService;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.encryption.AesUtil;
import cn.chiship.sdk.framework.base.BaseService;
import cn.chiship.sdk.framework.base.BaseController;
import cn.chiship.sdk.core.annotation.Authorization;

import javax.annotation.Resource;
import javax.validation.Valid;


import cn.chiship.framework.common.annotation.SystemOptionAnnotation;
import cn.chiship.framework.common.enums.BusinessTypeEnum;
import cn.chiship.framework.common.service.GlobalCacheService;
import cn.chiship.framework.upms.biz.system.entity.UpmsEmailSetting;
import cn.chiship.framework.upms.biz.system.entity.UpmsEmailSettingExample;
import cn.chiship.framework.upms.biz.system.pojo.dto.UpmsEmailSendTestDto;
import cn.chiship.framework.upms.biz.system.pojo.dto.UpmsEmailSettingDto;
import cn.chiship.sdk.third.core.model.EmailConfigModel;
import cn.chiship.sdk.third.other.EmailClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 三方邮件发送控制层
 * 2021/9/30
 *
 * @author lijian
 */
@RestController
@Authorization
@RequestMapping("/emailSetting")
@Api(tags = "三方邮件发送")
public class UpmsEmailSettingController extends BaseController<UpmsEmailSetting, UpmsEmailSettingExample> {

    @Resource
    private UpmsEmailSettingService upmsEmailSettingService;
    @Resource
    private CacheService cacheService;
    @Resource
    private GlobalCacheService globalCacheService;

    @Override
    public BaseService getService() {
        return upmsEmailSettingService;
    }


    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_SAVE, describe = "保存邮箱网关配置")
    @ApiOperation(value = "保存邮箱网关配置")
    @PostMapping(value = "save")
    public ResponseEntity<BaseResult> save(@RequestBody @Valid UpmsEmailSettingDto upmsEmailSettingDto) {

        UpmsEmailSetting upmsEmailSetting = new UpmsEmailSetting();
        BeanUtils.copyProperties(upmsEmailSettingDto, upmsEmailSetting);
        BaseResult baseResult = upmsEmailSettingService.insertSelective(upmsEmailSetting);
        if (baseResult.isSuccess()) {
            cacheService.cacheEmailSettingConfig();
        }
        return super.responseEntity(baseResult);

    }


    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_UPDATE, describe = "更新邮箱网关配置")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "主键", required = true, dataTypeClass = String.class, paramType = "path")
    })
    @ApiOperation(value = "更新邮箱网关配置")
    @PostMapping(value = "update/{id}")
    public ResponseEntity<BaseResult> update(@PathVariable("id") String id, @RequestBody @Valid UpmsEmailSettingDto upmsEmailSettingDto) {
        UpmsEmailSetting upmsEmailSetting = new UpmsEmailSetting();
        BeanUtils.copyProperties(upmsEmailSettingDto, upmsEmailSetting);
        upmsEmailSetting.setId(id);
        BaseResult baseResult = upmsEmailSettingService.updateByPrimaryKeySelective(upmsEmailSetting);
        if (baseResult.isSuccess()) {
            cacheService.cacheEmailSettingConfig();
        }
        return super.responseEntity(baseResult);
    }


    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_SAVE, describe = "系统邮件收发设置配置")
    @ApiOperation(value = "系统邮件收发设置配置")
    @PostMapping(value = "/configSystem")
    public ResponseEntity<BaseResult> config(@RequestBody @Valid UpmsEmailSettingDto upmsEmailSettingDto) {
        UpmsEmailSetting upmsEmailSetting = new UpmsEmailSetting();
        BeanUtils.copyProperties(upmsEmailSettingDto, upmsEmailSetting);
        BaseResult baseResult = upmsEmailSettingService.configSystemEmail(upmsEmailSetting);
        cacheService.cacheEmailSettingConfig();
        return super.responseEntity(baseResult);
    }

    @SystemOptionAnnotation(option = BusinessTypeEnum.SYSTEM_OPTION_OTHER, describe = "发送测试邮件")
    @ApiOperation(value = "发送测试邮件")
    @PostMapping(value = "/sendTest")
    public ResponseEntity<BaseResult> sendTest(@RequestBody @Valid UpmsEmailSendTestDto upmsEmailSendTestDto) {
        UpmsEmailSetting upmsEmailSetting = upmsEmailSettingService.selectByPrimaryKey(upmsEmailSendTestDto.getId());
        if (upmsEmailSetting == null) {
            return super.responseEntity(BaseResult.error("您还未配置邮箱发送网关"));
        }
        EmailConfigModel emailConfigModel = new EmailConfigModel(
                upmsEmailSetting.getHost(),
                upmsEmailSetting.getTransportProtocol(),
                upmsEmailSetting.getSmtpAuth() == 1,
                upmsEmailSetting.getSmtpPort(),
                upmsEmailSetting.getIsSsl() == 1,
                upmsEmailSetting.getSmtpSslPort(),
                upmsEmailSetting.getSendFromAddress(),
                AesUtil.aesEncode(upmsEmailSetting.getSendFromAddressPwd())
        );

        EmailClient emailClient = EmailClient.getInstance().config(emailConfigModel);
        BaseResult baseResult = emailClient.sendText(upmsEmailSendTestDto.getToAddress(), upmsEmailSetting.getSubject(), "邮箱网关配置测试发送邮件");
        return super.responseEntity(baseResult);
    }

    @SystemOptionAnnotation(describe = "根据外键id和类型查询邮箱信息")
    @ApiOperation("根据外键id和类型查询邮箱信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "outreachInfoId", value = "邮箱配置外键", required = true, dataTypeClass = String.class, paramType = "query"),
            @ApiImplicitParam(name = "type", value = "邮箱所属类别", required = true, dataTypeClass = String.class, paramType = "query")
    })
    @GetMapping(value = "/getEmailConfigByUserIdAndType")
    public ResponseEntity<BaseResult> getEmailConfigByUserIdAndType(
            @RequestParam(value = "outreachInfoId") String outreachInfoId,
            @RequestParam(value = "type") String type) {

        List<UpmsEmailSetting> listUpmsEmailSetting = upmsEmailSettingService.getEmailConfigByUserIdAndType(outreachInfoId, type);
        return super.responseEntity(BaseResult.ok(listUpmsEmailSetting));
    }
}
